package vcp.server.deamontasks;

import java.util.List;
import java.util.TimerTask;

import org.joda.time.DateTime;

import vcp.entity.Customer;
import vcp.entity.Subscription;
import vcp.server.DAO.CustomerDAO;
import vcp.server.DAO.SubscriptionDAO;
import vcp.server.interfaces.IServer;
import vcp.server.utility.CommunicationProvider;
import vcp.server.utility.SystemClock;

/**
 * 
 * @author VCP team
 *         <p>
 *         class that checks subscription if about to expire
 *         </p>
 */
public class EndOfSubscriptionTask extends TimerTask
{
	private final IServer server;
	private final CommunicationProvider emailProvider;

	/**
	 * class constructor
	 * 
	 * @param serverDeamon
	 */
	public EndOfSubscriptionTask ( IServer serverDeamon )
	{
		this.server = serverDeamon;
		this.emailProvider = new CommunicationProvider();
	}

	@Override
	public void run ()
	{
		synchronized (this.server.getDBLock())
		{
			System.out.println("EndOfSubscriptionTask:  TrueTime:" + new DateTime() + "  SysTime:" + SystemClock.getClockInstance().getSystemDateTime());
			SubscriptionDAO subscriberDAO = new SubscriptionDAO();
			List <Subscription> listOfSubscribers = subscriberDAO.findAllCasualFullSubscribers();
			if ( listOfSubscribers != null )
			{
				CustomerDAO customerDAO = new CustomerDAO();
				for ( Subscription subscription : listOfSubscribers )
				{
					if ( SystemClock.getClockInstance().daysBetweenCurrentDay(subscription.getEndDate()) == 7 )
					{
						Customer customer = customerDAO.findByID(subscription.getCustomerID());
						this.sendEmail(subscription, customer);
					}
				}
			}
		}
	}

	private void sendEmail ( Subscription subscription, Customer customer )
	{
		System.out.println("Email was send to:" + customer.getUserFirstName() + " to email address:" + customer.getUserEmail());

		String siteName = subscription.getSite() == null
														? ""
														: " to " + subscription.getSite().toString();

		String emailBody =
				"Dear Mr.\\Mrs. " + customer.getUserLastName()
						+ "\n\n"
						+ "You subscription period" + siteName
						+ "  will end a week from now on the " + subscription.getEndDate()
						+ "\n"
						+ "If you interested, you may renew your subscription"
						+ "\n\n"
						+ "Sincerely,"
						+ "\n"
						+ "VCP Inc.";

		if ( customer.getBalance() == - 100 )
		{
			this.emailProvider.sendEmail(subscription, customer, emailBody);
		}
	}
}
